<template>
  <div class="channel-editor-container">
    <div class="editor-header">
      <h3>通道名称自定义</h3>
      <p>正在为网关 <el-tag type="primary">{{ activeGatewayName }}</el-tag> 修改名称</p>
    </div>
    <el-scrollbar class="editor-body">
      <div v-if="modules.length > 0" class="channel-list">
        <div v-for="module in modules" :key="module.id" class="channel-item">
          <span class="channel-id-tag">通道 {{ module.id }}</span>
          <div class="channel-input-wrapper">
            <el-input
              v-model="editableNames[module.id]"
              placeholder="请输入自定义名称"
              maxlength="20"
              show-word-limit
              clearable
              @change="onNameChange(module.id)"
              @input="validateChannelName(module.id)"
            />
          </div>
        </div>
      </div>
      <el-empty v-else description="当前网关下没有可用的监测点"></el-empty>
    </el-scrollbar>
    <div class="editor-footer">
      <el-button @click="resetNames">重置更改</el-button>
      <el-button type="primary" @click="saveAllChanges" :disabled="!hasChanges">
        保存全部更改
      </el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, computed, onMounted, nextTick, onUnmounted } from 'vue';
import { moduleStore } from '@/store/module';
import { gatewayStore } from '@/store/gateway';
import { storeToRefs } from 'pinia';
import { ElMessage } from 'element-plus';
import { inject } from 'vue'
const props = defineProps<{
  alarmWorker: Worker | null;
}>();
const module_store = moduleStore();
const gateway_store = gatewayStore();

const { selectModule: modules } = storeToRefs(module_store);
const { activeGatewayId,currentIp } = storeToRefs(gateway_store);

// 使用一个本地的响应式对象来存储正在编辑的名称，避免直接修改store
const editableNames = ref<Record<number, string>>({});
const originalNames = ref<Record<number, string>>({});
const hasChanges = ref(false);

// 计算当前激活的网关名称
const activeGatewayName = computed(() => {
  const activeGateway = gateway_store.gatewayList.find(g => g.id === activeGatewayId.value);
  return activeGateway ? `${activeGateway.name} (${activeGateway.ip})` : '未知网关';
});

// 初始化或重置编辑状态
const initializeNames = async () => {
  const names: Record<number, string> = {};
  const originals: Record<number, string> = {};
  
  // 从 IndexedDB 加载已保存的名称
  const { channelNameDb } = await import('@/local/channelNameDb');
  const savedNames = await channelNameDb.getAllNames();
  
  const currentGatewayIp = gateway_store.currentIp;
  if (!currentGatewayIp) {
    console.warn('无法获取当前网关IP，无法初始化名称');
    return;
  }

  const currentModules = module_store.selectModule;
  currentModules.forEach(module => {
    const key = `${currentGatewayIp}-${module.id}`;
    const savedName = savedNames.get(key);
    const defaultName = `监测点${module.id}`;
    
    // 优先使用数据库中的名称，否则使用默认名称
    const currentName = savedName || defaultName;
    
    names[module.id] = currentName;
    originals[module.id] = currentName;
  });

  editableNames.value = names;
  originalNames.value = originals;
  hasChanges.value = false;
  console.log('重新初始化设备名称:', names);
};

// 当输入框内容变化时，检查是否有更改
const onNameChange = (moduleId: number) => {
  hasChanges.value = Object.keys(editableNames.value).some(
    id => editableNames.value[Number(id)] !== originalNames.value[Number(id)]
  );
};

// 验证通道名称长度
const validateChannelName = (moduleId: number) => {
  const name = editableNames.value[moduleId];
  if (name && name.length > 20) {
    editableNames.value[moduleId] = name.substring(0, 20);
    ElMessage.warning('通道名称不能超过20个字符');
  }
};

// 重置所有未保存的更改
const resetNames = () => {
  initializeNames();
  ElMessage.info('已重置所有未保存的更改');
};

// 保存所有更改
const saveAllChanges = async () => {
  if (!hasChanges.value) {
    ElMessage.warning('没有检测到任何更改');
    return;
  }

  const promises = [];
  for (const idStr in editableNames.value) {
    const id = Number(idStr);
    if (editableNames.value[id] !== originalNames.value[id]) {
      promises.push(
        module_store.updateChannelName(activeGatewayId.value, id, editableNames.value[id])
      );
    }
  }

  try {
    await Promise.all(promises);
    ElMessage.success('所有更改已成功保存！');
    
    // 通知 alarmWorker 更新名称映射 - 修复：使用最新的编辑后的名称
    const { channelNameDb } = await import('@/local/channelNameDb');
    const allDeviceNames = await channelNameDb.getAllNames();
    const deviceNameMapObject = Object.fromEntries(allDeviceNames);
    
    // 通知报警列表需要重新映射名称
    const customEvent = new CustomEvent('update_device_names');
    window.dispatchEvent(customEvent);
    if (props.alarmWorker) {
      props.alarmWorker.postMessage({
        type: 'update_device_names',
        data: {
          payload: deviceNameMapObject
        }
      });
    } else {
      console.warn('alarmWorker 未初始化或为空');
    }
    
    // 🔥 新增：通知其他组件设备名称已更新
    const deviceNameUpdateEvent = new CustomEvent('device_name_updated');
    window.dispatchEvent(deviceNameUpdateEvent);
    
    // 强制重新初始化，确保界面显示最新的名称
    await nextTick();
    // 添加短暂延迟确保 store 更新完成
    setTimeout(() => {
      initializeNames();
      console.log('界面已更新为最新的设备名称');
    }, 100);
  } catch (error) {
    console.error('保存通道名称时出错:', error);
    ElMessage.error('保存失败，请检查控制台获取更多信息');
  }
};

// 监听模块列表或活动网关的变化，以重新初始化编辑器
watch([() => module_store.selectModule, activeGatewayId], initializeNames, { deep: true });

// 额外监听 store 中的设备名称变化
watch(() => module_store.selectModule.map(m => m.deviceName), () => {
  console.log('检测到设备名称变化，重新初始化界面');
  initializeNames();
}, { deep: true });

// 组件挂载时立即初始化
onMounted(initializeNames);


</script>

<style scoped lang="less">
.channel-editor-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px;
}

.editor-header {
  margin-bottom: 20px;
  h3 {
    font-size: 22px;
    margin-bottom: 8px;
  }
  p {
    font-size: 14px;
    color: #888;
  }
}

.editor-body {
  flex: 1;
  min-height: 0;
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 10px;
}

.channel-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.channel-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 10px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.channel-id-tag {
  flex-shrink: 0;
  font-weight: bold;
  color: #555;
  background-color: #eee;
  padding: 6px 12px;
  border-radius: 4px;
}

.channel-input-wrapper {
  flex-grow: 1;
}

.editor-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}
</style>
